package com.example;

import org.I0Itec.zkclient.ZkClient;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

//##ServerScoekt服务端
public class ZkServerScoekt implements Runnable {
    private static int port = 18084;

    public static void main(String[] args) throws IOException {
        ZkServerScoekt server = new ZkServerScoekt(port);
        Thread thread = new Thread(server);
        thread.start();
    }

    public ZkServerScoekt(int port) {
        this.port = port;
    }

    //注册服务
    public void regServer() {
        //1.建立连接
        ZkClient zkClient = new ZkClient("127.0.0.1:2181", 5000, 10000);
        //2.先创建父节点
        String root = "/hello";
        if (!zkClient.exists(root)) {
            //如果父节点不存在，则创建父节点
            zkClient.createPersistent(root);
        }
        //3.创建子节点
        String nodeName = root + "/test_" + port;
        String nodeValue = "127.0.0.1:" + port;
        if (zkClient.exists(nodeName)) {
            //如果存在该子节点 则删除
            zkClient.delete(nodeName);
        }
        //如果子节点不存在，则创建子节点  只能是临时节点  可用于dubbo的服务发现
        zkClient.createEphemeral(nodeName, nodeValue);
        System.out.println("服务注册成功!");
    }

    public void run() {
        ServerSocket serverSocket = null;
        try {
            regServer();
            serverSocket = new ServerSocket(port);
            System.out.println("Server start port:" + port);
            Socket socket = null;
            while (true) {
                socket = serverSocket.accept();
                new Thread(new ServerHandler(socket)).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (Exception e2) {

            }
        }
    }

}